<template>
  <div class="fullschedule-container" ref="fullscheduleContainer" :style="fscStyle">
    <div class="fsc-root">
      <fscheader
        :checkbox-show="checkboxShow"
        :is-edit="isEdit"
        :is-copy="isCopy"
        :appo-repair="appoRepair"
        :all-ckb="allCkb"
        :season-cur.sync="seasonCur"
        :checked-all.sync="checkedAll"
        :edit-show="editShow"
        :scheduledata="scheduledata"
        :status-template="statusTemplate"
        @HeaderColAll="HeaderColAll"
        @copyInsert="copyInsert"
        @seasonChange="seasonChange"
        @checkedAllChange="headerCheckedAllChange(true)"
      ></fscheader>
      <div class="fsc-container">
        <fscmain
          v-show="sidebardata.length>0"
          :checkbox-show="checkboxShow"
          :overdue="overdue"
          :is-edit="isEdit"
          :is-add="isAdd"
          :appo-repair="appoRepair"
          :all-ckb="allCkb"
          :scheduledata="scheduledata"
          :sidebardata="sidebardata"
          :status-template="statusTemplate"
          :release-is-edit="true"
          :status-filter.sync="statusFilter"
          :quick-temp-obj="quickTempObj"
          @checkAllHalfDay="checkAllHalfDay"
          @appoClick="appoClick"
          @checkBoxChange="checkBoxChange"
          @appoDel="appoDel"
          @appoAdd="appoAdd"
          @sidebarHideChange="sidebarHideChange"
          v-on="$listeners"
        ></fscmain>
        <div v-show="sidebardata.length===0" class="ky-listnone">暂无数据~</div>
      </div>
    </div>
    <commonTipDialog :dialog-tip-visible="dialogTipVisible" :content="tipContent" @closeTipEvent="closeTipEvent"></commonTipDialog>
  </div>
</template>
<!--
  预约排班组件
  rowHeight 设置 显示的行高
  isEdit 设置是否可以编辑 默认 true
  isAdd 设置 是否可以新增 默认 true
  delSend 设置 是否可以删除时段模板
  checkboxShow  设置 头部是否显示复选框
  statusFilter 设置 判断需要显示的数据，跟时段状态对应
  statusTemplate 设置模板类型:
    schedule:编辑类型，预约排班设置时的模板
    template:模板类型，视图模板、已发布排班模板、导入查看模板
-->
<script>
// import bus from '@/api/bus'
import { mapGetters } from 'vuex'
import { getHolidayList } from '@/api/api'
import fscheader from './fscheader'
import fscmain from './fscmain'
import commonTipDialog from '@/components/dialog/commonTipDialog'
import {
  getWeekStartEndDate,
  calMaxMinTime,
  calAppoInitialNum,
  calNewAppoTime,
  calTimeSelected,
  getCalTimeMinute,
  getInitTimeGroud,
  calAppoStyleObj,
  getArgsCalNum,
  getSeasonDateInfo,
  getSeasonDateTitle,
  getAppointmentSametype,
  getScheduleAppoSametype,
  getAppointmentSametypeOnline,
  getScheduleAppoSametypeOnline,
  flattenDeep,
  getSeasonDefault,
  getContinuityNum,
  timeTransferInterval
} from '@/utils/schedule'
import { setLocalStorage, getLocalStorage } from '@/utils/localStorage'
import { getSidebarDataThisDay, isNull, getSidebarDataTemp, getSidebarData, filterDuplicates } from '@/utils/utils' // this.$utils
import { getDefaultRoom } from '@/utils/auth'
import { dateFormatter } from '@/utils/validate'
let channelSplitKey = '、'
const originObj = {
  // appoSize: 'normal', // mini\ normal
  'id': 0,
  'hospitalCode': '', // 医院编号
  'recordCode': '', // 编码
  'depArea': '', // 影像区域
  'dep': '', // 检查部门
  'modality': '', // 检查设备
  'checkRoom': '', // 检查机房
  'appointmentDate': '', // 检查日期
  'week': '', // 星期几
  'checkClass': '', // 检查班次
  'beginTime': '', // 检查开始时间
  'endTime': '', // 检查结束时间
  'initialNum': 0, // 初始号码
  'checkNum': 0, // 检查数量
  'reserveNum': 0, // 预留数量
  'addNum': 0, // 追加数量
  'callNum': 0, // 已预约数量
  'totalNum': 0, // 号源总数
  'color': '', // 颜色
  'operatorName': '', // 操作人
  'operatorDate': '', // 操作时间
  'appointmentStatus': '', // 预约时段状态:暂停预约、节假日、正常预约、设备故障、计划排班
  'remark1': '',
  'remark2': '',
  'remark3': '',
  'season': '1', // 时令
  'department': '' // 所属科室
}
// const timegatherLineObj = {
//   height: 60,
//   heightpx: '84px',
//   preKey: '',
//   startNum: 1,
//   time: '00:00-24:00'
// }
export default {
  components: {
    fscmain,
    fscheader,
    commonTipDialog
  },
  props: {
    rowHeight: {
      type: Number,
      default: 64
    },
    // 预约时段列表，显示为左边菜单
    // sidebardata: {
    //   type: Array,
    //   default() {
    //     return [
    //       //   {
    //       //     title: '上午班',
    //       //     start: '8:00',
    //       //     end: '12:00',
    //       //     barHeight: 0,
    //       //     timegather: []
    //       //   }
    //     ]
    //   }
    // },
    // 快速排班的号源条件模板数据
    quickTempObj: {
      type: Object,
      default: null
    },
    // 本周排版是否过期
    overdue: {
      type: Boolean,
      default: false
    },
    // 是否可编辑
    isEdit: {
      type: Boolean,
      default: true
    },
    // 是否可复制
    isCopy: {
      type: Boolean,
      default: false
    },
    // 是否可新增
    isAdd: {
      type: Boolean,
      default: true
    },
    // 是否强制显示所有日期可选
    allCkb: {
      type: Boolean,
      default: false
    },
    // 是否显示头部编辑图标
    editShow: {
      type: Boolean,
      default: false
    },
    // 是否显示头部复选框
    checkboxShow: {
      type: Boolean,
      default: false
    },
    // 判断需要显示的数据
    statusFilter: {
      type: String,
      default: ''
    },
    statusTemplate: {
      type: String,
      default: 'schedule'
    },
    delSend: {
      type: Boolean,
      default: false
    },
    hospitalCode: {
      type: String,
      default: ''
    },
    // 模板排列，定位、日按顺序排
    appoRepair: {
      type: Boolean,
      default: false
    }
    // appoContinuation: {
    //   // 判断号源是否连续设置
    //   type: Boolean,
    //   default: false
    // }
  },
  data() {
    return {
      parametersValuesSplit: this.$store.state.user.parametersValuesSplit,
      tipContent: '',
      dialogTipVisible: false,
      fscStyle: { height: 'calc(100vh - 320px)' },
      isChanged: false, // 判断模板数据是否有修改，提交时可以做拦截判断提示
      currDate: dateFormatter(new Date(), false),
      curWeekDate: '',
      checkedAll: false,
      week: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'],
      seasonCur: '',
      sidebardata: [],
      monthHoliday: {},
      weekDate: [], // 一周的日期,计算出来后在表格头部展示
      /**
       * 预约时段,号源的主体数据
       * date：日期
       * week: 星期
       * holiday: 节假日
       * season: 时令 1：冬令时，2：夏令时
       * disable: 今天是否可编辑
       * checkedAll: 是否全选当前日期整列
       * rest: 是否是否休息
       * appointmentTotal: 号源总是
       * appointment：预约时段数据列表, 数据格式: [时段 [时间段 [时段号源数据 {}]]]
      */
      scheduledata: [],
      quickTempObjFul: null, // 判断最初开发时，模拟加数据

      // 当前选择坐标暂存数据
      sidebarIndex: null,
      scheduleIndex: null,
      appoIndex: null,
      timeIndex: null,

      appoFormData: {
        HospitalCode: '',
        StartDate: '',
        EndDate: '',
        DepArea: '',
        Dep: '',
        Modality: '',
        ModalityType: '',
        CheckRoom: '',
        AppointmentStatus: '', // 预约时段状态:暂停预约、节假日、正常预约、设备故障、计划排班；单选
        IsHasFilters: true
      },
      isCheckedIds: []
    }
  },
  computed: {
    ...mapGetters(['appoContinuation', 'isContinuityNum']),
    appConfig() {
      return this.$store.state.settings.appConfig
    },
    unAddDepList() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.unAddDepList || []
    }
  },
  created() {
    // // // console.log('checkboxShow_in_index.vue--created', this.checkboxShow)
    // this.init(this.newDate)
    // // // console.log('进入 fullschedule Page')
  },
  mounted() {
    // // // console.log('checkboxShow_in_index.vue--mounted', this.checkboxShow)
    // // // console.log('打印scheduledata', this.scheduledata)
  },
  methods: {
    // 关闭提示弹窗
    closeTipEvent() {
      this.dialogTipVisible = false
    },
    // item勾选状态改变
    checkBoxChange(data) {
      // // // console.log('勾选状态改变', data)
      const { isChecked, scheduleIndex, sidebarIndex, appoIndex } = data
      let id = this.scheduledata[scheduleIndex].appointment[sidebarIndex][appoIndex].id
      // // // console.log('this.scheduledata[scheduleIndex].appointment[sidebarIndex]', this.scheduledata[scheduleIndex].appointment[sidebarIndex])
      // // // console.log('id', id)
      // this.isCheckedIds 所多选的号源id，用来判断当前是否多选
      if (!isChecked) {
        // 如果有一个不勾选，header的checkbox也为不勾选
        this.scheduledata[scheduleIndex].checkedAll = false
        // 如果有一个不勾选，一键勾选半天的checkbox也为不勾选
        this.scheduledata[scheduleIndex].checkedAllHalf[sidebarIndex] = false
        let idIndex = this.isCheckedIds.indexOf(id)
        if (idIndex > -1) {
          this.isCheckedIds.splice(idIndex, 1)
        }
      } else {
        this.isCheckedIds.push(id)
      }
      // // // console.log('this.isCheckedIds', this.isCheckedIds)
      // // // console.log('然后改变列表值，然后再传入item')
      this.scheduledata[scheduleIndex].appointment[sidebarIndex][appoIndex].isChecked = isChecked
      // 判断是否勾选/取消勾选header的全选checkbox
      let isAllChecked = true
      this.scheduledata[scheduleIndex].appointment.forEach(checkClassData => {
        checkClassData.forEach(item => {
          if (!item.isChecked && !item.isAddBox) {
            isAllChecked = false
          }
        })
      })
      // 如果遍历当天所有的号源后，isAllChecked依然是true,则header的checkbox勾选，否则不勾选
      if (isAllChecked) {
        this.scheduledata[scheduleIndex].checkedAll = true
      } else {
        this.scheduledata[scheduleIndex].checkedAll = false
      }
      // 判断是否勾选/取消勾选一键勾选半天的全选checkbox
      let isAllCheckedHalfDay = true
      // // console.log('this.scheduledata[scheduleIndex].appointment[sidebarIndex]', this.scheduledata[scheduleIndex].appointment[sidebarIndex])
      this.scheduledata[scheduleIndex].appointment[sidebarIndex].forEach(item => {
        if (!item.isChecked && !item.isAddBox) {
          isAllCheckedHalfDay = false
        }
      })
      // 如果遍历当天所有的号源后，isAllCheckedHalfDay依然是true,则一键勾选半天的checkbox勾选，否则不勾选
      if (isAllCheckedHalfDay) {
        this.scheduledata[scheduleIndex].checkedAllHalf[sidebarIndex] = true
      } else {
        this.scheduledata[scheduleIndex].checkedAllHalf[sidebarIndex] = false
      }
      // // // console.log('isAllChecked', isAllChecked)
      // // // console.log('this.scheduledata[scheduleIndex].checkedAll', this.scheduledata[scheduleIndex].checkedAll)
      // // console.log('改变后的scheduledata', this.scheduledata)
      this.$emit('checkedIdChange', this.isCheckedIds)
    },
    // 全选半天的号源
    checkAllHalfDay(data) {
      // // console.log('index.vue=>checkAllHalfDay', data)
      const { scheduleIndex, sidebarIndex } = data
      // // console.log('sidebarIndex', sidebarIndex)
      // this.scheduledata[scheduleIndex].appointment[sidebarIndex].checkedAll = !this.scheduledata[scheduleIndex].appointment[sidebarIndex].checkedAll
      // 然后，还需要把appointment里面的每个时段的号源都勾选一下，就是isChecked都设置为true
      // 这里特别需要注意的是：需要根据sidebarIndex来判断，号源的时段，比如是早上的还是下午的
      this.scheduledata[scheduleIndex].appointment.forEach((timeFrameData, indexSidebar) => {
        if (indexSidebar == sidebarIndex) {
          timeFrameData.forEach((item, index) => {
            // 排除【新增号源】按钮
            if (!item.isAddBox) {
              // // console.log('this.scheduledata[scheduleIndex].checkedAllHalf[sidebarIndex]', this.scheduledata[scheduleIndex].checkedAllHalf[sidebarIndex])
              item.isChecked = this.scheduledata[scheduleIndex].checkedAllHalf[sidebarIndex]
              // this.isCheckedIds 所多选的号源id，用来判断当前是否多选
              let id = item.id
              // 被选中的id的加减算法
              if (item.isChecked) {
                let idIndex = this.isCheckedIds.indexOf(id)
                if (idIndex == -1) {
                  this.isCheckedIds.push(id)
                }
              } else {
                let idIndex = this.isCheckedIds.indexOf(id)
                if (idIndex > -1) {
                  this.isCheckedIds.splice(idIndex, 1)
                }
              }
            }
          })
        }
      })
      this.$emit('checkedIdChange', this.isCheckedIds)
      // // console.log('this.isCheckedIds', this.isCheckedIds)
      this.scheduledata = JSON.parse(JSON.stringify(this.scheduledata))
    },
    // 列全选
    HeaderColAll(data) {
      const { index } = data
      this.scheduledata[index].checkedAll = !this.scheduledata[index].checkedAll
      let halfDayKey = Object.keys(this.scheduledata[index].checkedAllHalf)
      // 然后，还需要把appointment里面的每个时段的号源都勾选一下，就是isChecked都设置为true
      this.scheduledata[index].appointment.forEach(timeFrameData => {
        timeFrameData.forEach(item => {
          // 排除【新增号源】按钮
          if (!item.isAddBox) {
            item.isChecked = this.scheduledata[index].checkedAll
            // this.isCheckedIds 所多选的号源id，用来判断当前是否多选
            let id = item.id
            // 被选中的id的加减算法
            if (this.scheduledata[index].checkedAll) {
              let idIndex = this.isCheckedIds.indexOf(id)
              if (idIndex == -1) {
                this.isCheckedIds.push(id)
              }
              halfDayKey.forEach(item => {
                this.scheduledata[index].checkedAllHalf[item] = true
              })
            } else {
              let idIndex = this.isCheckedIds.indexOf(id)
              if (idIndex > -1) {
                this.isCheckedIds.splice(idIndex, 1)
              }
              halfDayKey.forEach(item => {
                this.scheduledata[index].checkedAllHalf[item] = false
              })
            }
          }
        })
      })
      this.$emit('checkedIdChange', this.isCheckedIds)
      // // // console.log('this.isCheckedIds', this.isCheckedIds)
      this.scheduledata = JSON.parse(JSON.stringify(this.scheduledata))
      // // // console.log('this.scheduledata', this.scheduledata)
      this.headerCheckedAllChange(false)
      // this.$forceUpdate()
    },
    // 全选
    headerCheckedAllChange(change) {
      // // console.log('headerCheckedAllChange', change)
      let ckb = true
      this.scheduledata.forEach(item => {
        if (!item.disable || this.allCkb) {
          if (change) {
            item.checkedAll = this.checkedAll
          } else if (!item.checkedAll) {
            ckb = false
          }
        }
      })
      if (change) {
        this.scheduledata = JSON.parse(JSON.stringify(this.scheduledata))
      } else {
        this.checkedAll = ckb
      }
      this.$emit('checkedAllChange')
    },
    // 编辑|查看详情, 预约号源
    appoClick(data) {
      // // console.log('编辑|查看详情, 预约号源appoClick_data', data) // timeIndex
      const { sidebarIndex, scheduleIndex, appoIndex, sItem } = data.info
      this.sidebarIndex = sidebarIndex
      this.scheduleIndex = scheduleIndex
      this.appoIndex = appoIndex
      // // // console.log('sidebarIndex', sidebarIndex)
      // // // console.log('this.sidebardata[sidebarIndex]', this.sidebardata[sidebarIndex])
      // // // console.log('appoClick:=====', sidebarIndex, scheduleIndex, appoIndex, sItem)
      // const tg = appoNew || this.sidebardata[sidebarIndex].timegather[scheduleIndex]
      // // // // console.log('tg', tg)
      let _time = sItem.beginTime + '-' + sItem.endTime
      const _startTime = this.appoRepair ? '00:00' : this.sidebardata[sidebarIndex].start
      const _endTime = this.appoRepair ? '24:00' : this.sidebardata[sidebarIndex].end
      const _disable = this.scheduledata[scheduleIndex].disable
      // 去除当前数据
      const appos = this.scheduledata[scheduleIndex].appointment[sidebarIndex]
      const appoArr = JSON.parse(JSON.stringify(appos))
      const curAppoIndex = appoArr.findIndex(appoItem => appoItem.beginTime === sItem.beginTime && appoItem.endTime === sItem.endTime)
      if (curAppoIndex >= 0) {
        this.timeIndex = curAppoIndex
        appoArr.splice(curAppoIndex, 1)
      }
      // 计算当前时间段可选择的时间范围
      _time = calMaxMinTime(_time, appoArr, _startTime, _endTime)
      // // // console.log('appoClick appoArr', appoArr)
      // // // console.log('appoClick _time', _time)
      // // // console.log('_startTime, _endTime', _startTime, _endTime)
      // const timeOpt = calMaxMinTime(_time, appos, _startTime, _endTime)
      const timeSel = this.sidebardata[sidebarIndex].start + '-' + this.sidebardata[sidebarIndex].end// '08:00-12:00'
      // // // console.log('timeSel in click edit', timeSel)
      // setLocalStorage('yjyy-appoItem', JSON.stringify(sItem))
      this.$emit('handleAppoInfo', { appoInfo: sItem, timeSel: timeSel, time: _time, disableDate: _disable, isCheckedIds: this.isCheckedIds })
    },
    // 新增，排班
    async appoAdd(data) {
      // // console.log('新增按钮触发，排班appoAdd')
      const { sidebarIndex, scheduleIndex, timeIndex, appoNew } = data
      this.sidebarIndex = sidebarIndex
      this.scheduleIndex = scheduleIndex
      this.timeIndex = timeIndex
      this.appoIndex = null
      // // console.log('sidebarIndex====>', sidebarIndex)
      // // console.log('this.sidebardata====>', this.sidebardata)
      const tg = appoNew || this.sidebardata[sidebarIndex].timegather[timeIndex]
      const seasonInfo = getSeasonDateInfo(this.scheduledata[scheduleIndex], tg.time)
      const startNum = this.statusTemplate !== 'template' ? seasonInfo ? seasonInfo.startNum : tg.startNum : tg.startNum
      const _startTime = this.appoRepair ? '00:00' : this.sidebardata[sidebarIndex].start
      const _endTime = this.appoRepair ? '24:00' : this.sidebardata[sidebarIndex].end
      // // // // console.log('appoAdd:====', sidebarIndex, scheduleIndex, timeIndex)
      if (!this.quickTempObj && !this.quickTempObjFul) {
        let _time = tg.time
        const _week = this.week[scheduleIndex]
        const _checkClass = this.sidebardata[sidebarIndex].title
        // 计算当前时间段可选择的时间范围
        const appos = this.appoRepair ? this.scheduledata[scheduleIndex].appointment : this.scheduledata[scheduleIndex].appointment[sidebarIndex]
        const timeOpt = calMaxMinTime(_time, appos, _startTime, _endTime)
        const timeSel = calTimeSelected(_time, timeOpt) // '08:00-12:00'
        // // // console.log('appoAdd in fullschedule——————timeSel', timeSel)
        // // // console.log('appoAdd in fullschedule', _time, appos, _startTime, _endTime)
        // 没有快捷模板，新增预约时段号源。弹出框进行设置
        this.$emit('addNewSchedule', { time: timeOpt, timeSel: timeSel, week: _week, checkClass: _checkClass, startNum: startNum })
        return
      }
      // 有选择快捷模板，直接用快捷模板数据赋值
      const nObj = Object.assign({}, this.quickTempObj)
      const dateAppoData = this.scheduledata[scheduleIndex]
      const appoArr = this.scheduledata[scheduleIndex].appointment[sidebarIndex]
      // 设置初始号码，设置时段获取的时段初始号码
      nObj.initialNum = startNum * 1 // 初始号码
      nObj.startNum = startNum * 1
      nObj.preKey = tg.preKey
      if (this.quickTempObj) {
        // 判断为已改变，提交时做判断是否提交更新
        this.isChanged = true
        let _time = tg.time
        const etime = timeTransferInterval(nObj.beginTime, nObj.endTime, _time.split('-')[0])
        // // // console.log('etimeetimeetimeetime', etime)
        nObj.id = 0
        nObj.timestamp = new Date().getTime() + Math.random()
        nObj.secTime = etime
        nObj.beginTime = _time.split('-')[0]
        nObj.endTime = _time.split('-')[1]
        nObj.week = this.week[scheduleIndex]
        // nObj.initialNum = 0
        nObj.addNum = 0 // 追加设置 为0
        nObj.checkNum = nObj.checkNum * 1 // 检查数量
        nObj.reserveNum = nObj.reserveNum * 1 // 预留数量
        nObj.callNum = nObj.callNum * 1 // 已预约数量
        nObj.remark2 = nObj.recordCode
        nObj.status = '启用' // 状态
        nObj.appointmentStatus = ''
        nObj.appointmentDate = dateAppoData.dateFull + ' 00:00:00'
        nObj.checkClass = this.sidebardata[sidebarIndex].title
      }
      // // // // console.log('appoArr=======>12345678', appoArr)
      // 计算当前添加参数模板的班次时间
      const _nObj = await calNewAppoTime(appoArr, nObj, _startTime, _endTime)
      // // // console.log('this.sidebardata[sidebarIndex]', this.sidebardata[sidebarIndex])
      // const timeObj = this.appoRepair ? { start: '00:00', end: '24:00' } : this.sidebardata[sidebarIndex]
      const timeObj = this.sidebardata[sidebarIndex]
      const nnobj = calAppoStyleObj(timeObj, _nObj, this.rowHeight)
      if (nnobj) {
        // 班次名称判断转换
        const appoTitle = getSeasonDateTitle({
          appointmentDate: nnobj.appointmentDate,
          beginTime: nnobj.beginTime,
          endTime: nnobj.endTime,
          checkClassData: this.sidebardata
        })
        nnobj.checkClass = appoTitle || nnobj.checkClass
        const _appoArr = appoArr ? appoArr.concat([nnobj]) : [nnobj]
        // 获取排班号源初始号码排序数据
        this.scheduledata[scheduleIndex].appointment[sidebarIndex] = _appoArr
        const resSche = await this.getAppoByTypes(this.scheduledata[scheduleIndex].appointment, nnobj.checkClass, this.scheduledata[this.scheduleIndex].dateFull)
        this.scheduledata[scheduleIndex].appointment = resSche
        this.scheduledata = JSON.parse(JSON.stringify(this.scheduledata))
        // 计算预约号源的当天总数
        this.calAppoTotal(this.scheduledata)
      }
    },
    // 重新排号
    getAppoByTypes(a, b, d) {
      return new Promise(async resolve => {
        // // console.log('this.appoRepair', this.appoRepair) // this.appoRepair = true
        const resAppo = this.appoRepair
          ? await getAppointmentSametypeOnline(a, this.appoContinuation, this.sidebardata, d)
          : await getAppointmentSametype(a, b, this.appoContinuation, this.sidebardata, d)
        resolve(resAppo)
      })
    },
    /**
     * @param {Object} a 一周的号源模板数据
     * @param {Object} _sbData 时间轴
     */
    getScheByTypes(a, _sbData, isTemp) {
      // // console.log('getScheByTypes=>_sbData', _sbData)
      return new Promise(async resolve => {
        // checkClassData 排班列表竖向的时间维度
        // getScheduleAppoSametypeOnline(scheduledata, continuation, checkClassData)
        // // // console.log('打印排班列表竖向的时间维度=>this.sidebardata', this.sidebardata)
        const resSche = this.appoRepair
          ? await getScheduleAppoSametypeOnline(a, this.appoContinuation, _sbData || this.sidebardata, isTemp) // 现在都是使用这个函数
          : await getScheduleAppoSametype(a, this.appoContinuation, _sbData || this.sidebardata) // 该函数返回不了数据，有问题
        // const resSche = await getScheduleAppoSametypeOnline(a, this.appoContinuation, _sbData || this.sidebardata)
        // // console.log('getScheByTypes=>resSche', resSche)
        resolve(resSche)
      })
    },
    // 时间出错的数据回写判断
    insertError(errordata) {
      return new Promise(async resolve => {
        // // // console.log('errordata', errordata)
        const appoOldData = JSON.parse(JSON.stringify(this.scheduledata))
        const insertData = JSON.parse(JSON.stringify(errordata))
        let insertLen = insertData.length
        const _week = this.week
        const errorList = []
        if (insertLen === 0) {
          resolve()
          return
        }
        const insertRun = async () => {
          const iAppo = insertData.shift()
          if (insertLen === 0 && !iAppo) {
            // 结束
            // // // console.log('errorList:', errorList)
            this.scheduledata = await this.getScheByTypes(appoOldData)
            this.$emit('appoErrorListChange', errorList)
            this.isChanged = true
            resolve()
            return
          }
          try {
            // 错误的数据获取不到 sidebarIndex，需要重新计算
            let sidebarIndex = this.calSidebarIndex(iAppo)
            // 判断日期，获取日期索引
            let scheduleIndex = _week.findIndex(w => w === iAppo.week)
            if (sidebarIndex < 0 || scheduleIndex < 0) {
              errorList.push(iAppo)
              return
            }
            const _startTime = this.sidebardata[sidebarIndex].start
            const _endTime = this.sidebardata[sidebarIndex].end
            let appoArr = appoOldData[scheduleIndex].appointment[sidebarIndex]
            let insertTime = iAppo.beginTime + '-' + iAppo.endTime
            // 计算时段号源在当前时段区间内的可设置的时间段区间
            const appos = this.appoRepair ? appoOldData[scheduleIndex].appointment : appoOldData[scheduleIndex].appointment[sidebarIndex]
            const _time = calMaxMinTime(insertTime, appos, _startTime, _endTime)
            if (_time) {
              // const nObj = Object.assign({}, iAppo)
              // const oObj = appoOldData[scheduleIndex].appointment[sidebarIndex]
              // 新老号源时间段对比
              const oTs = getCalTimeMinute(iAppo.beginTime)
              const oTe = getCalTimeMinute(iAppo.endTime)
              const nTs = getCalTimeMinute(_time.split('-')[0])
              const nTe = getCalTimeMinute(_time.split('-')[1])
              // // // // console.log(oTs, oTe)
              // // // // console.log(nTs, nTe)
              if (oTs >= nTs && oTe <= nTe) {
                // 时段号源的时间段在时间区间内
                iAppo.isBad = false
                // const timeObj = this.appoRepair ? { start: '00:00', end: '24:00' } : this.sidebardata[sidebarIndex]
                const timeObj = this.sidebardata[sidebarIndex]
                const nnobj = calAppoStyleObj(timeObj, iAppo, this.rowHeight)
                if (nnobj) {
                  appoArr = appoArr ? appoArr.concat([nnobj]) : [nnobj]
                  appoOldData[scheduleIndex].appointment[sidebarIndex] = appoArr
                }
              } else {
                // 时段号源的时间段超出时间区间
                errorList.push(iAppo)
              }
            } else {
              // 时段号源的时间段超出时间区间
              iAppo.oldBeginTime = iAppo.beginTime
              iAppo.oldEndTime = iAppo.endTime
              errorList.push(iAppo)
            }
          } catch (err) {
            // // // console.log(err)
            errorList.push(iAppo)
          }
        }
        // 开始执行任务
        while (insertLen >= 0) {
          insertRun()
          insertLen -= 1
        }
      })
    },
    // 删除,预约号源
    async appoDel(data) {
      // // console.log('appoDel_data', data)
      const { sidebarIndex, scheduleIndex, appoIndex, sItem } = data
      // // console.log(`appoDel=>sidebarIndex:${sidebarIndex},scheduleIndex:${scheduleIndex},appoIndex:${appoIndex},sItem:${sItem}`)
      this.sidebarIndex = sidebarIndex
      this.scheduleIndex = scheduleIndex
      this.appoIndex = appoIndex
      // // console.log('delSend', this.delSend)
      if (sItem.id && this.delSend) {
        this.$emit('handleAppoDel', sItem)
      } else {
        if (this.scheduledata[scheduleIndex].appointment[sidebarIndex].length > 0) {
          this.scheduledata[scheduleIndex].appointment[sidebarIndex].splice(appoIndex, 1)
        }
        const resSche = await this.getScheByTypes(this.scheduledata)
        // // console.log('resSch', resSche)
        this.scheduledata = JSON.parse(JSON.stringify(resSche))
        // 计算预约号源的当天总数
        this.calAppoTotal(this.scheduledata)
        // 判断为已改变，提交时做判断是否提交更新
        this.isChanged = true
      }
    },
    appoDelSuccessCb() {
      this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex].splice(this.appoIndex, 1)
      // 计算预约号源的当天总数
      this.calAppoTotal(this.scheduledata)
      // 判断为已改变，提交时做判断是否提交更新
      this.isChanged = true
    },
    // 复制其他日期的时段号源
    copyInsert(data) {
      this.$emit('copyInsertChange', data)
    },
    // 时令切换，班次时间段更新
    async seasonChange(season) {
      // // // console.log(season)
      // const resSeason = await getSeasonSchedule(season)
      // // // console.log('获取时间轴getSeasonSchedule', resSeason)
      const _sidebardata = getSidebarData() || getSidebarDataTemp() // resSeason.sidebardata
      // 班次时段更新
      await this.initSidebar(_sidebardata)
      // 号源重新插入
      let appodata = []
      this.scheduledata.forEach(sche => {
        let iScheAppoArr = sche.appointment
        iScheAppoArr = flattenDeep(iScheAppoArr)
        appodata.push(iScheAppoArr)
      })
      appodata = flattenDeep(appodata)
      this.appoPull(appodata, true)
    },
    resetAppoStatus(status, from) {
      this.scheduledata.forEach(item => {
        const appos = item.appointment
        // 批量维护全天的情况
        // if (item.checkedAll) {
        //   appos.forEach(appoSche => {
        //     appoSche.forEach(appo => {
        //       // if (appo.appointmentStatus !== '正常预约') {
        //       //   appo.appointmentStatus = status
        //       // }
        //       if (from == 'temp') {
        //         appo.status = status
        //         // // // console.log('appo.status', appo.status)
        //       } else {
        //         appo.appointmentStatus = status
        //         // // // console.log('appo.appointmentStatus', appo.appointmentStatus)
        //       }
        //     })
        //   })
        // } else { // 批量维护半天的情况

        // }
        appos.forEach(appoSche => {
          appoSche.forEach(appo => {
            // if (appo.appointmentStatus !== '正常预约') {
            //   appo.appointmentStatus = status
            // }
            if (appo.isChecked) {
              if (from == 'temp') {
                appo.status = status
                // // // console.log('appo.status', appo.status)
              } else {
                appo.appointmentStatus = status
                // // // console.log('appo.appointmentStatus', appo.appointmentStatus)
              }
            }
          })
        })
      })
      // // // console.log('this.scheduledata', this.scheduledata)
      // this.appoPull(this.scheduledata)
      // 判断为已改变，提交时做判断是否提交更新
      this.isChanged = true
    },
    // 同步时令设置时段参数
    appoSyncSet() {
      // // // console.log('同步时令设置时段参数')
      this.isChanged = true
      const seasonInfo = getSeasonDefault()
      const isCN = getContinuityNum()
      // // // // console.log(seasonInfo)
      // 获取第一个时段 班次
      const getCheckClass = (appointment) => {
        let cc = ''
        let idx = -1
        const len = appointment.length
        for (let i = 0; i < len; i++) {
          const appos = appointment[i]
          if (appos.length > 0) {
            cc = appos[0].checkClass
            idx = i
            return { cc: cc, idx: idx }
          }
        }
        return { cc: cc, idx: idx }
      }
      // 获取时令班次初始号码
      const getInitialNum = (checkClass) => {
        let startNum = ''
        const sdObj = seasonInfo.checkClassSettings[`${checkClass}`]
        if (sdObj) {
          const sdd = sdObj.numberSettings
          startNum = sdd ? sdd[0].startNum : ''
        }
        return startNum
      }

      // // // // console.log(JSON.parse(JSON.stringify(this.scheduledata)))
      this.scheduledata.forEach(async sche => {
        if (isCN) {
          const { cc, idx } = getCheckClass(sche.appointment)
          const startNum = getInitialNum(cc)
          // // // // console.log(startNum)
          if (startNum >= 0 && idx >= 0) {
            sche.appointment[idx][0].initialNum = startNum
            sche.appointment = await this.getAppoByTypes(sche.appointment, cc, sche.dateFull)
          }
        } else {
          let keys = {}
          let scheAppos = JSON.parse(JSON.stringify(sche.appointment))
          scheAppos.forEach(async (appos, scheIdx) => {
            if (appos.length > 0) {
              let cc = ''
              appos.forEach(appo => {
                if (!keys[`${appo.checkClass}`]) {
                  keys[`${appo.checkClass}`] = true
                  cc = appo.checkClass
                  const startNum = getInitialNum(appo.checkClass)
                  // // // console.log(startNum)
                  if (startNum >= 0) {
                    appo.initialNum = startNum
                  }
                }
              })
              if (cc) {
                sche.appointment = await this.getAppoByTypes(scheAppos, cc, sche.dateFull)
              }
            }
          })
        }
      })
      // // // console.log('解析后的scheduledata数据', JSON.parse(JSON.stringify(this.scheduledata)))
    },
    // 删除选中日期的所有号源
    async appoDelDay() {
      this.isChanged = true
      let _sidebardata = this.sidebardata
      this.scheduledata.forEach(sche => {
        // // console.log('appoDelDay=>sche', sche)
        if (sche.checkedAll) {
          sche.appointment = this.getAppointentArr(_sidebardata)
        } else {
          sche.appointment.forEach((appoItem, index) => {
            sche.appointment[index] = appoItem.filter(it => it.isChecked == false)
            // sche.appointment[index] = appoItem.filter(it => {
            //   let idIndex = this.isCheckedIds.indexOf(it.id)
            //   if (idIndex == -1) {
            //     return it
            //   } else {
            //     this.isCheckedIds.splice(idIndex, 1)
            //   }
            // })
          })
        }
      })
      const resSche = await this.getScheByTypes(this.scheduledata)
      this.scheduledata = JSON.parse(JSON.stringify(resSche))
      // this.scheduledata = JSON.parse(JSON.stringify(this.scheduledata))
    },
    // 添加新的排班号源
    async addNew(appoObj, isTemp) {
      // // console.log('addNew')
      let sidebarDasta = isTemp ? getSidebarDataTemp() : getSidebarData()
      // 这里需要判断号源的班次
      const appoTitle = getSeasonDateTitle({
        appointmentDate: null,
        beginTime: appoObj.beginTime,
        endTime: appoObj.endTime,
        checkClassData: sidebarDasta
      })
      appoObj.checkClass = appoTitle

      sidebarDasta.forEach((item, index) => {
        if (item.title == appoObj.checkClass) {
          this.sidebarIndex = index
        }
      })
      // if (appoObj.checkClass == '凌晨班') {
      //   this.sidebarIndex = 0
      // } else if (appoObj.checkClass == '上午班') {
      //   this.sidebarIndex = 1
      // } else if (appoObj.checkClass == '下午班') {
      //   this.sidebarIndex = 2
      // }
      // // // console.log('添加单条号源点确定按钮后触发addNew函数appoObj', appoObj)
      // // // console.log('这里拿到的号源里已经改变了班次名称，需往上找原因')
      const _obj = Object.assign({}, appoObj)
      // // // console.log(`beginTime~endTime:${_obj.beginTime}~${_obj.endTime}`)
      // // // console.log('++++++++++++++添加新的排班号源addNew————_obj', _obj)
      this.appoIndex = null
      // // // console.log(`把this.scheduledata[${this.scheduleIndex}].appointment[${this.sidebarIndex}]赋值给appoData`)
      // // // console.log('this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex]', this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex])
      let appoData = [...this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex]]
      // // // console.log('appoData——concat之前--刚刚赋值过来', appoData)
      // // // console.log('this.sidebarIndex', this.sidebarIndex)
      // // // console.log('this.sidebardata[this.sidebarIndex]', this.sidebardata[this.sidebarIndex])
      // const timeObj = this.appoRepair ? { start: '00:00', end: '24:00' } : this.sidebardata[this.sidebarIndex] // 原来是这句
      const timeObj = this.sidebardata[this.sidebarIndex] // 20231102修改后用这句
      // // // console.log('当前时间轴timeObj', timeObj)
      // // // console.log('然后要把_obj经过calAppoStyleObj函数加工赋值给nnobj')
      // // // console.log(`beginTime~endTime:${_obj.beginTime}~${_obj.endTime}`)
      const nnobj = calAppoStyleObj(timeObj, _obj, this.rowHeight)
      // // // console.log('然后要把nnobj合并到appoData中')
      // // // console.log('+++++++++++++++++添加号源nnobj++++++++++++++++++', nnobj)
      if (nnobj) {
        const dateAppoData = this.scheduledata[this.scheduleIndex]
        nnobj.id = 0
        nnobj.timestamp = new Date().getTime() + Math.random()
        nnobj.week = this.week[this.scheduleIndex]
        nnobj.addNum = 0 // 追加设置 为0
        nnobj.status = nnobj.status ? nnobj.status : '启动' // 状态
        nnobj.appointmentStatus = nnobj.appointmentStatus ? nnobj.appointmentStatus : ''
        nnobj.appointmentDate = dateAppoData.dateFull + ' 00:00:00'
        // // // console.log(`this.sidebardata[${this.sidebarIndex}].title`, this.sidebardata[this.sidebarIndex].title)
        nnobj.checkClass = this.sidebardata[this.sidebarIndex].title
        // // // console.log('nnobj.checkClass', nnobj.checkClass)
        nnobj.remark2 = ''
        nnobj.recordCode = ''
        nnobj.color = ''
        // const appoTitle = getSeasonDateTitle({
        //   appointmentDate: nnobj.appointmentDate,
        //   beginTime: nnobj.beginTime,
        //   endTime: nnobj.endTime
        // })
        // // // // console.log('==appoTitle==', appoTitle)
        // nnobj.checkClass = appoTitle || nnobj.checkClass
        // // // console.log('appoData_concat之前', appoData)
        appoData = appoData ? appoData.concat([nnobj]) : [nnobj]
        // // // console.log('appoData_concat之后', appoData)
        // // // console.log('这里数据就出问题了')
        // 获取排班号源初始号码排序数据
        this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex] = appoData
        // // // console.log(`appoData赋值给this.scheduledata[${this.scheduleIndex}].appointment[${this.sidebarIndex}]`)
        // // // console.log(this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex])
        const appos = await this.getAppoByTypes(this.scheduledata[this.scheduleIndex].appointment, nnobj.checkClass, this.scheduledata[this.scheduleIndex].dateFull)
        // // // console.log('this.scheduledata[this.scheduleIndex].appointment通过getAppoByTypes函数处理后得到appos', appos)
        this.scheduledata[this.scheduleIndex].appointment = appos
        // // // console.log(`appos赋值给this.scheduledata[${this.scheduleIndex}].appointment`)
        // // // console.log(this.scheduledata[this.scheduleIndex].appointment)
        this.scheduledatacalAppoTotal = JSON.parse(JSON.stringify(this.scheduledata)) // await this.getScheByTypes(this.scheduledata)
        // 计算预约号源的当天总数
        this.calAppoTotal(this.scheduledata)
        // 判断为已改变，提交时做判断是否提交更新
        this.isChanged = true
      }
    },
    /**
     * @param {Object} appointmentFilters 批量加减号源的过滤条件(包括部位和预约原来的限制)
     */
    batchAddSubAppoFilters(ruleParams) {
      // 批量加：拿到过滤条件等规则后，进行与原有的规则对比，若之前未设置则直接加，若之前有设置，则跳过（但遇到parametersType=dengjipart/BIGPART的时候，部位值相同则去重)
      // 批量减 拿到过滤条件等规则候，进行与原有的规则对比，有相同则减
      console.log('batchAddSubAppoFilters=>ruleParams', ruleParams)
      console.log('this.scheduledata', this.scheduledata)
      // const fileterChannel = ['WYYY', 'LCYY', 'VIP', 'newAll', 'YYLY']
      // let tipList = []
      this.scheduledata.forEach((todayScheduleData, indexToday) => {
        todayScheduleData.appointment.forEach((timeFrameData, indexTimeFrame) => {
          timeFrameData.forEach((item, index) => {
            // 若该号源被勾选，则修改部位信息
            if (item.isChecked) {
              // item.appointmentFilters = ruleParams.appointmentFilters
              // this.isChanged = true
              if (ruleParams.batchType == 'add') {
                console.log(ruleParams.batchType)
                // 批量加：拿到过滤条件等规则后，进行与原有的规则对比，若之前未设置则直接加，若之前有设置，则跳过（但遇到parametersType=dengjipart/BIGPART的时候，部位值相同则去重)
                // 另外，还要考虑预约来源，多选也是用、隔开的(parametersType=WYYY/LCYY/VIP/newAll/YYLY)
                ruleParams.appointmentFilters.forEach(newFilterItem => {
                  console.log('newFilterItem', newFilterItem)
                  const findItem = item.appointmentFilters.find(findItem => findItem.parametersType == newFilterItem.parametersType)
                  const findItemIndex = item.appointmentFilters.findIndex(findItem => findItem.parametersType == newFilterItem.parametersType)
                  console.log('findItem', findItem)
                  if (isNull(findItem)) {
                    console.warn('批量加=>newFilterItem', newFilterItem)
                    this.scheduledata[indexToday].appointment[indexTimeFrame][index].appointmentFilters.push(newFilterItem)
                    this.isChanged = true
                  } else {
                    this.isChanged = true
                    // 然后把相同的过滤名称-对象给找出来
                    if (findItem.parametersValues != newFilterItem.parametersValues) {
                      let unionStr = ''
                      let unionArr = []
                      // 对过滤条件的判断sex的加需要为覆盖
                      if (newFilterItem.parametersType == 'AgeEnd' || newFilterItem.parametersType == 'AgeBegin') {
                        findItem.parametersValues = newFilterItem.parametersValues
                      } else {
                        if (newFilterItem.parametersType == 'dengjipart' || newFilterItem.parametersType == 'BIGPART') {
                          // 检查部位的标点符号
                          unionArr = [...new Set([...findItem.parametersValues.split(this.parametersValuesSplit), ...newFilterItem.parametersValues.split(this.parametersValuesSplit)])]
                          unionStr = unionArr.join(this.parametersValuesSplit)
                        } else {
                          unionArr = [...new Set([...findItem.parametersValues.split(channelSplitKey), ...newFilterItem.parametersValues.split(channelSplitKey)])]
                          unionStr = unionArr.join(channelSplitKey)
                        }
                      }
                      // 对部位的判断 || 对预约来源的判断
                      // if (newFilterItem.parametersType == 'dengjipart' || newFilterItem.parametersType == 'BIGPART' || fileterChannel.includes(newFilterItem.parametersType)) {
                      // }
                      if (unionStr) {
                        console.log('unionStr', unionStr)
                        findItem.parametersValues = unionStr
                      }
                      console.warn('批量加=>findItem', findItem)
                      this.scheduledata[indexToday].appointment[indexTimeFrame][index].appointmentFilters[findItemIndex] = findItem
                      // item.newFilterItem = findItem
                      // tipList.push(item)
                    }
                  }
                })
                // item.appointmentFilters.forEach(filterItem => {
                //   if (filterItem.parametersName == '') {}
                // })
              } else { // sub
                // 批量减 拿到过滤条件等规则候，进行与原有的规则对比，有相同则减
                // 批量减：拿到过滤条件等规则后，进行与原有的规则对比，若之前有设置过则直接减，若之前没有设置，则跳过（但遇到parametersType=dengjipart/BIGPART的时候，需要额外处理)
                console.log(ruleParams.batchType)
                ruleParams.appointmentFilters.forEach(newFilterItem => {
                  console.log('newFilterItem', newFilterItem)
                  const findItem = item.appointmentFilters.find(findItem => findItem.parametersType == newFilterItem.parametersType)
                  const findItemIndex = item.appointmentFilters.findIndex(findItem => findItem.parametersType == newFilterItem.parametersType)
                  console.log('findItem', findItem)
                  if (isNull(findItem)) {
                    // this.scheduledata[indexToday].appointment[indexTimeFrame][index].appointmentFilters.push(newFilterItem)
                    // this.isChanged = true
                  } else {
                    console.log('findItemIndex', findItemIndex)
                    this.isChanged = true
                    // 然后把相同的过滤名称-对象给找出来
                    if (findItem.parametersValues != newFilterItem.parametersValues) {
                      let unionStr = ''
                      let unionArr = ''
                      // if (newFilterItem.parametersType == 'sex') {} else {}
                      if (newFilterItem.parametersType == 'dengjipart' || newFilterItem.parametersType == 'BIGPART') {
                        unionArr = filterDuplicates(findItem.parametersValues.split(this.parametersValuesSplit), newFilterItem.parametersValues.split(this.parametersValuesSplit))
                        unionStr = unionArr.join(this.parametersValuesSplit)
                      } else {
                        unionArr = filterDuplicates(findItem.parametersValues.split(channelSplitKey), newFilterItem.parametersValues.split(channelSplitKey))
                        unionStr = unionArr.join(channelSplitKey)
                      }

                      if (unionStr) {
                        console.log('unionStr', unionStr)
                        findItem.parametersValues = unionStr
                      }
                      console.warn('批量减============001=>findItem', findItem)
                      if (isNull(unionStr)) {
                        // 合并后的结果为空则删除
                        this.scheduledata[indexToday].appointment[indexTimeFrame][index].appointmentFilters.splice(findItemIndex, 1)
                      } else {
                        // 合并后的结果还有内容则替换
                        this.scheduledata[indexToday].appointment[indexTimeFrame][index].appointmentFilters[findItemIndex] = findItem
                      }
                    } else {
                      console.log('sub============002')
                      console.log('splice')
                      console.log('批量减splice before', this.scheduledata[indexToday].appointment[indexTimeFrame][index].appointmentFilters)
                      this.scheduledata[indexToday].appointment[indexTimeFrame][index].appointmentFilters.splice(findItemIndex, 1)
                      console.log('splice after', this.scheduledata[indexToday].appointment[indexTimeFrame][index].appointmentFilters)
                    }
                  }
                })
              }
            }
          })
        })
      })
      // console.log('tipList', tipList)
      console.log('this.scheduledata', this.scheduledata)
      console.log('emit=>closeTempDlg')
      this.$emit('closeTempDlg')
      // if (ruleParams.batchType == 'add') {
      //   console.log(ruleParams.batchType)
      // } else {
      //   console.log(ruleParams.batchType)
      // }
    },
    // 编辑保存的数据更新，更新数据
    async editUpdate(appoObj) {
      // // console.log('==编辑确认按钮点击后进入editUpdate==', appoObj)
      // 编辑之前先判断，是否有多选
      if (this.isCheckedIds.length >= 1) {
        this.$confirm('当前存在勾选号源, 若进行编辑，只会一起修改被勾选号源的限制条件，请确认是否要继续?', '提示', {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 找到被勾选的号源
          this.scheduledata.forEach(todayScheduleData => {
            todayScheduleData.appointment.forEach(timeFrameData => {
              timeFrameData.forEach((item, index) => {
                // 若该号源被勾选，则修改部位信息
                if (item.isChecked) {
                  item.appointmentFilters = appoObj.appointmentFilters
                  this.isChanged = true
                }
              })
            })
          })
          this.$store.dispatch('app/toggleTempVisible', false)
        }).catch(() => {})
      } else {
        // 编辑单条号源数据的时候
        const _obj = Object.assign({}, appoObj)
        let appoData = [...this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex]]
        // const timeObj = this.appoRepair ? { start: '00:00', end: '24:00' } : this.sidebardata[this.sidebarIndex]
        const timeObj = this.sidebardata[this.sidebarIndex]
        const nnobj = calAppoStyleObj(timeObj, _obj, this.rowHeight)
        if (nnobj) {
          // 去除当前数据
          let appoArr = JSON.parse(JSON.stringify(this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex]))
          if (this.timeIndex >= 0) {
            appoArr.splice(this.timeIndex, 1)
          }
          appoData = appoArr ? appoArr.concat([nnobj]) : [nnobj]
          // console.log('getDefaultRoom=>', getDefaultRoom())
          this.statusTemplate !== 'template' && this.tipFunction(appoData, nnobj)
          // 获取排班号源初始号码排序数据
          this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex] = JSON.parse(JSON.stringify(appoData))
          // 重新排号
          const appos = await this.getAppoByTypes(this.scheduledata[this.scheduleIndex].appointment, nnobj.checkClass, this.scheduledata[this.scheduleIndex].dateFull)
          this.scheduledata[this.scheduleIndex].appointment = appos
          this.scheduledata = JSON.parse(JSON.stringify(this.scheduledata))
          // // console.log('编辑this.scheduledata', this.scheduledata)
          // 计算预约号源的当天总数
          this.calAppoTotal(this.scheduledata)
          // 判断为已改变，提交时做判断是否提交更新
          this.isChanged = true
        }
        this.$store.dispatch('app/toggleTempVisible', false)
      }
    },
    tipFunction(appoData, nnobj) {
      // // console.log('tipFunction=>appoData', appoData)
      // // console.log('tipFunction=>nnobj', nnobj)
      // 判断当前时段号源的排队号会不会超过下一个班次号源的起始排队号，若超过，提示加号源的操作者，是否要这么做
      let isOverNextAppo = false
      // let isLastAppo = true
      appoData.forEach(item => {
        // // console.log('item.beginTime', item.beginTime)
        // // console.log('nnobj.beginTime', nnobj.beginTime)
        // // console.log('item.beginTime > nnobj.beginTime', item.beginTime > nnobj.beginTime)
        if (item.beginTime > nnobj.beginTime) {
          if ((nnobj.initialNum + nnobj.totalNum) > item.initialNum) {
            isOverNextAppo = true
          }
          // isLastAppo = false
        }
        // // console.log('isOverNextAppo', isOverNextAppo)
      })
      // || (isLastAppo && this.isContinuityNum)
      if (isOverNextAppo) {
        let tipInfo = '此次操作增加号源后，将会影响到下一个时段号源的排队号，建议在该班次的最后一个时段去增加号源！此次是否确认要修改?'
        let tipInfo2 = '此次操作增加号源后，将会影响到下一个时段号源的排队号，建议在该班次的最后一个时段去增加号源！此次修改将会被系统拦截！'
        if (!this.isContinuityNum) {
          tipInfo = '此次操作增加号源后，将会影响到下一个时段号源的排队号，建议在该班次的最后一个时段去增加号源！此次是否确认要修改?'
          tipInfo2 = '此次操作增加号源后，将会影响到下一个时段号源的排队号，建议在该班次的最后一个时段去增加号源！此次修改将会被系统拦截！'
        } else {
          tipInfo = '此次操作增加号源后，将会影响到下一个时段号源的排队号，建议在当天的最后一个时段去增加号源！此次是否确认要修改?'
          tipInfo2 = '此次操作增加号源后，将会影响到下一个时段号源的排队号，建议在当天的最后一个时段去增加号源！此次修改将会被系统拦截！'
        }
        const defaultRoom = getDefaultRoom()
        // defaultRoom[2].indexOf('CT') > -1 || defaultRoom[2].indexOf('内窥镜') > -1
        if (this.unAddDepList.indexOf(defaultRoom[2].split('-')[2]) > -1) {
          this.$confirm(tipInfo2, '提示', {
            confirmButtonText: '已知晓',
            cancelButtonText: '取消',
            type: 'warning'
          }).then((e) => {
            if (e == 'confirm') {
              window.location.reload()
            } else {
              window.location.reload()
            }
          }).catch((e) => {
            // // console.log('catch=>e', e)
            if (e == 'cancel') {
              window.location.reload()
            }
          })
          return
        }
        this.$confirm(tipInfo, '提示', {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((e) => {
          // ......
          // // console.log('e', e)
          if (e == 'confirm') {
            // ......
            this.$store.dispatch('app/toggleTempVisible', false)
          } else {
            // ......
            window.location.reload()
          }
        }).catch((e) => {
          // // console.log('catch=>e', e)
          if (e == 'cancel') {
            window.location.reload()
          }
        })
      }
    },
    // 批量编辑保存的数据更新，更新数据
    async batchUpdate(data, index) {
      this.scheduledata[index].appointment = data
      this.scheduledata = JSON.parse(JSON.stringify(this.scheduledata))
      // this.$parent.checkedAppoData = [this.scheduledata[index]]
      // 计算预约号源的当天总数
      this.calAppoTotal(this.scheduledata)
      // 判断为已改变，提交时做判断是否提交更新
      this.isChanged = true
    },
    // 追加号源数
    setDateNumUpdate(num = 20, sidebarIndex, checkNumEditType, updateField) {
      // // console.log('setDateNumUpdate')
      // // console.log(`num = ${num}, sidebarIndex = ${sidebarIndex}, checkNumEditType = ${checkNumEditType}`)
      // // // console.log('JSON.stringify(this.scheduledata)', JSON.stringify(this.scheduledata))
      const _scheduledata = this.scheduledata // JSON.parse(JSON.stringify(this.scheduledata))
      // // // console.log('待查看_scheduledata111', _scheduledata)
      // // // console.log('待查看_scheduledata_jsonStringify', JSON.stringify(_scheduledata))
      const _len = _scheduledata.length
      let count = 0
      // // console.log('_len:', _len)
      return new Promise(async resolve => {
        // // // console.log('待查看this.sidebardata', this.sidebardata)
        // const sdbtitle = sidebarIndex || sidebarIndex === 0 ? this.sidebardata[sidebarIndex].title : ''
        let sdbtitle = ''
        if (sidebarIndex === '') {
          sdbtitle = ''
        } else {
          this.sidebardata.forEach((item, index) => {
            if (index == sidebarIndex) {
              sdbtitle = item.title
            }
          })
        }
        // // // // console.log(sdbtitle)
        const start = () => {
          return new Promise(async resolve => {
            // // // // console.log('count:', count)
            if (count >= _len) {
              resolve()
              return false
            }
            let sdata = _scheduledata[count]
            // // console.log('sdata-begin', sdata)
            let appointment = sdata.appointment
            // // console.log('appointment', appointment)
            const apposLen = appointment.length
            // 批量维护全天的情况
            // if (apposLen > 0 && sdata.checkedAll && num) {
            //   // 判断当前日期是否选中 checkedAll
            //   for (let i = 0; i < apposLen; i++) {
            //     const appoArr = appointment[i]
            //     const aLen = appoArr.length
            //     if ((typeof sidebarIndex === 'number' && i === sidebarIndex) || (!sidebarIndex && sidebarIndex !== 0)) {
            //       for (let j = 0; j < aLen; j++) {
            //         const appoObj = appoArr[j]
            //         if (!sdbtitle || sdbtitle === appoObj.checkClass) {
            //           // 判断是为追加，如果不是则赋值修改
            //           appoObj.checkNum = checkNumEditType ? appoObj.checkNum * 1 + num * 1 : num * 1
            //           appoObj.totalNum = getArgsCalNum(appoObj.checkNum, appoObj.reserveNum, appoObj.addNum, appoObj.callNum)
            //           // 获取排班号源初始号码排序数据
            //           const newSchedule = await calAppoInitialNum(appoArr, sdbtitle, this.appoContinuation, this.sidebardata, i)
            //           // 重新赋值
            //           sdata.appointment[i] = newSchedule
            //         }
            //       }
            //     }
            //   }
            // }
            // 批量维护勾选的情况
            if (apposLen > 0 && num) {
              // 判断当前日期是否选中 checkedAll
              for (let i = 0; i < apposLen; i++) {
                const appoArr = appointment[i]
                const aLen = appoArr.length
                if ((typeof sidebarIndex === 'number' && i === sidebarIndex) || (!sidebarIndex && sidebarIndex !== 0)) {
                  for (let j = 0; j < aLen; j++) {
                    // const appoObj = appoArr[j]
                    // // console.log('sdbtitle', sdbtitle)
                    // // console.log('appoObj.checkClass', appoObj.checkClass)
                    // // console.log('appoObj.isChecked', appoObj.isChecked)
                    if (appoArr[j].isChecked) {
                      // 判断是为追加，如果不是则赋值修改
                      appoArr[j][updateField] = checkNumEditType ? appoArr[j][updateField] * 1 + num * 1 : num * 1
                      appoArr[j].totalNum = getArgsCalNum(appoArr[j].checkNum, appoArr[j].reserveNum, appoArr[j].addNum, appoArr[j].callNum)
                    }
                  }
                  // 获取排班号源初始号码排序数据
                  const newSchedule = await calAppoInitialNum(appoArr, sdbtitle, this.appoContinuation, this.sidebardata, i)
                  // 重新赋值
                  sdata.appointment[i] = newSchedule
                }
              }
            }
            // // console.log('sdata-end', sdata)
            resolve()
          })
        }
        while (count < _len) {
          await start(_scheduledata)
          count += 1
        }
        // 计算预约号源的当天总数
        this.calAppoTotal(_scheduledata)
        // 判断为已改变，提交时做判断是否提交更新
        this.isChanged = true
        // // // console.log('待查看_scheduledata222', _scheduledata)
        // // // console.log('待查看_scheduledata222_jsonStringify', JSON.stringify(this._scheduledata))
        this.scheduledata = await this.getScheByTypes(_scheduledata)
        // // // console.log('待查看_scheduledata333', this.scheduledata)
        // // // console.log('待查看_scheduledata333_jsonStringify', JSON.stringify(this.scheduledata))
        resolve(true)
      })
    },

    // 初始化
    init(data) {
      return new Promise(async resolve => {
        let _sidebardata = data.sidebardata
        this.curWeekDate = data.date
        this.checkedAll = false
        this.seasonCur = data.seasonTxt || ''
        // 计算一周的日期，weekDate
        this.weekDate = []
        // // // console.log('==this.curWeekDate', this.curWeekDate)
        this.weekDate = await getWeekStartEndDate(this.curWeekDate)
        // // // console.log('==this.weekDate==拿到本周的日期', this.weekDate)
        // 计算周的节假日
        const weekHoliday = await this.calWeekHoliday()
        let sdata = []
        const appointen = this.getAppointentArr(_sidebardata)
        // // // console.log('==appointen==计算班次', appointen)
        // this.weekDate ['2023-10-30', '2023-10-31', '2023-11-01', '2023-11-02', '2023-11-03', '2023-11-04', '2023-11-05']
        // 通过一周日期，给每天赋值初始值对象
        this.weekDate.forEach((item, index) => {
          const _date = item
          const _disable = new Date(item).getTime() < new Date(this.currDate).getTime()
          const _obj = {
            date: _date.substring(5).replace('-', '/'),
            dateFull: item,
            week: this.week[index],
            holiday: false,
            disable: _disable,
            season: 1,
            checkedAll: false,
            rest: weekHoliday.indexOf(_date) >= 0,
            appointmentTotal: 0,
            appointment: appointen
          }
          sdata.push(_obj)
        })
        this.scheduledata = JSON.parse(JSON.stringify(sdata))
        // // // console.log('##this.scheduledata##初始化了appointment##', this.scheduledata)
        this.$emit('checkedAllChange')
        // 左边时段
        this.initSidebar(_sidebardata)
        resolve()
      })
    },
    // 初始化时间轴
    initSidebar(sbd) {
      return new Promise(resolve => {
        if (sbd && typeof sbd === 'object') {
          sbd.forEach(item => {
            const resData = getInitTimeGroud(item, this.rowHeight)
            item.zanc = JSON.parse(JSON.stringify(resData))
            item.timegather = item.sidebarHide ? resData.htg : resData.stg
            item.barHeight = item.sidebarHide ? resData.hbh : resData.sbh
          })
          this.sidebardata = JSON.parse(JSON.stringify(sbd)) // getSidebarData() // JSON.parse(JSON.stringify(sbd))
          // // console.log('this.sidebardata==', this.sidebardata)
          this.$nextTick(() => {
            this.$_resizeHandler_fsc()
          })
        }
        resolve()
      })
    },
    // 计算周预约号源每天的总预约号源数，
    calAppoTotal(scheduledata) {
      return new Promise(resolve => {
        scheduledata.forEach((item, index) => {
          let total = 0
          let callNum = 0
          let zqNum = 0
          let callNumZq = 0
          // 号源统计区分上下午的对象
          let appoInfoForStatistics = {
            callNum: {},
            total: {},
            zqNum: {},
            callNumZq: {}
          }
          const appos = flattenDeep(item.appointment).filter(ap => !ap.isAddBox)
          if (appos.length > 0) {
            appos.forEach(appo => {
              // 去除已预约号源数 checkNum-检查数量 reserveNum-预留数量 initialNum-初始号码 callNum-已预约数量
              const t = appo.checkNum * 1 + appo.reserveNum * 1 + appo.addNum * 1
              total += t
              // 已预约
              if (appo.callNum) {
                callNum += appo.callNum * 1
              }
              // 增强
              const checkType = this.validAppoCheckType(appo)
              if (checkType) {
                zqNum += t
                callNumZq += appo.callNum ? appo.callNum * 1 : 0
              }
              // 上面是历史代码，下面是新增的需求，号源统计区分上下午
              if (Object.keys(appoInfoForStatistics.callNum).indexOf(appo.checkClass) > -1) {
                appoInfoForStatistics.callNum[appo.checkClass] += appo.callNum * 1
                appoInfoForStatistics.total[appo.checkClass] += t
                if (checkType) {
                  appoInfoForStatistics.zqNum[appo.checkClass] += t
                  appoInfoForStatistics.callNumZq[appo.checkClass] += appo.callNum ? appo.callNum * 1 : 0
                } else {
                  appoInfoForStatistics.zqNum[appo.checkClass] = 0
                  appoInfoForStatistics.callNumZq[appo.checkClass] = 0
                }
              } else {
                appoInfoForStatistics.callNum[appo.checkClass] = appo.callNum * 1
                appoInfoForStatistics.total[appo.checkClass] = t
                if (checkType) {
                  appoInfoForStatistics.zqNum[appo.checkClass] = t
                  appoInfoForStatistics.callNumZq[appo.checkClass] = appo.callNum ? appo.callNum * 1 : 0
                } else {
                  appoInfoForStatistics.zqNum[appo.checkClass] = 0
                  appoInfoForStatistics.callNumZq[appo.checkClass] = 0
                }
              }
            })
          }
          item.appointmentTotal = total // 日-未预约号源数
          item.appointmentCallTotal = callNum // 日-已预约号源数
          item.appointmentTotalZq = zqNum // 增强，日-未预约号源数
          item.appointmentCallTotalZq = callNumZq // 增强，日已预约号源数
          item.appoInfoForStatistics = appoInfoForStatistics
          // // // console.log('appoInfoForStatistics', appoInfoForStatistics)
          // const apposDiff = flattenDeep(item.appointment).filter(ap => !ap.isAddBox)
          // // // console.log('calAppoTotal_appos', appos)
          // if (appos.length > 0) {
          //   appos.forEach(appo => {
          //     // 去除已预约号源数 checkNum-检查数量 reserveNum-预留数量 initialNum-初始号码 callNum-已预约数量
          //     const t = appo.checkNum * 1 + appo.reserveNum * 1 + appo.addNum * 1
          //     total += t
          //     // 已预约
          //     if (appo.callNum) {
          //       callNum += appo.callNum * 1
          //     }
          //     // 增强
          //     const checkType = this.validAppoCheckType(appo)
          //     if (checkType) {
          //       zqNum += t
          //       callNumZq += appo.callNum ? appo.callNum * 1 : 0
          //     }
          //   })
          // }
        })
        resolve()
      })
    },
    validAppoCheckType(row) {
      const _filters = row.appointmentFilters
      let checkClass = ''
      if (_filters && _filters.length > 0) {
        _filters.forEach(item => {
          if (item.parametersType === 'CheckType' && item.parametersValues.indexOf('增强') >= 0) {
            checkClass = 'check_zq'
          }
        })
      }
      return checkClass
    },
    // 计算班次,号源数组
    getAppointentArr(sidebardata) {
      let _appo = []
      let _len = sidebardata ? sidebardata.length : 1
      for (let i = 0; i < _len; i++) {
        _appo[i] = []
      }
      return _appo
    },
    // 获取、计算当前周的节假日情况
    calWeekHoliday() {
      return new Promise(async resolve => {
        if (this.statusTemplate !== 'schedule') {
          resolve([])
          return
        }
        const _week = JSON.parse(JSON.stringify(this.weekDate))
        this.monthHoliday = {}
        const _len = _week.length
        let weekHoliday = []
        for (let i = 0; i < _len; i++) {
          const ym = _week[i].substring(0, 7)
          if (!this.monthHoliday[ym]) {
            this.monthHoliday[ym] = await this.getHolidayListPost(ym)
          }
          const dIndex = this.monthHoliday[ym].findIndex(item => item.holiday.substring(0, 10) === _week[i])
          if (dIndex >= 0) {
            weekHoliday.push(_week[i])
          }
        }
        resolve(weekHoliday)
      })
    },
    // 获取月节假日
    getHolidayListPost(month) {
      return new Promise(async resolve => {
        const params = {
          HospitalCode: this.hospitalCode,
          Month: month
        }
        let resMonth = []
        await getHolidayList(params).then(res => {
          if (res && res.code === 10000) {
            resMonth = res.content.list
          }
        })
        resolve(resMonth)
      })
    },
    initData(data) {
      // let bigpartlist = JSON.parse(getLocalStorage('BIGPARTLIST'))
      // // // // console.log('bigpartlist', bigpartlist)
      // // // console.log('initData_into', data)
      // const unAf = window.g.DISLODGE_APPOINTMENT_FILTER || ['VIPNUM']
      const appos = data // JSON.parse(JSON.stringify(data))
      // // // console.log('initData_into——appos', appos)
      appos.filter(ad => !ad.isAddBox).forEach(appo => {
        // && item.parametersType == 'dengjipart'
        // appo.appointmentFilters = appo.appointmentFilters.filter(apf => !unAf.includes(apf.parametersType)).filter(item => item.parametersName != '检查项目')
        let aflts = appo.appointmentFilters
        // let aflts_new = []
        let parametersTypeByPart = getLocalStorage('parametersTypeByPart')
        // this.$store.state.user.parametersTypeByPartKey2.toLowerCase()
        // 如果是温州市中心医院将大部位值替换成dengjipart且不判断小部位的配置
        if (parametersTypeByPart == 'dengjipart') {
          aflts.filter(item => (item.parametersType == 'dengjipart'))
          appo.appointmentFilters = aflts
        }
        // for (let i = 0; i < appo.appointmentFilters.length; i++) {
        //   if (appo.appointmentFilters[i].parametersName === '检查部位' && this.$store.state.user.parametersTypeByPartKey2.toLowerCase() == 'dengjipart') {
        //     if (appo.appointmentFilters[i].parametersValues) {
        //       let parametersValues = appo.appointmentFilters[i].parametersValues.split()
        //       let parametersValuesNew = []
        //       parametersValues.forEach(item => {
        //         if (bigpartlist.indexOf(item) > -1) {
        //           parametersValuesNew.push(item)
        //         }
        //       })
        //       // appo.appointmentFilters[i].parametersValues = parametersValuesNew.join()
        //       // // // // console.log('appo.appointmentFilters[i].parametersValues__END', appo.appointmentFilters[i].parametersValues)
        //     }
        //   }
        // }
        // // // // console.log('==appo.appointmentFilters==', appo.appointmentFilters)
      })
      // // // console.log('initData_into——appos——return', appos)
      return appos
    },
    /**
     * 计算时间的分钟数
     * @param {*} time 时间 10:00
     * return 600 (10*60 + 0*1)
     */
    getCalTimeMinute(time) {
      if (!time) return 0
      const _t = time.split(':')
      return _t[0] * 60 + _t[1] * 1
    },
    // 数据推入判断执行方法
    /**
     * @param {Object} appoData 号源数据源
     * @param {Object} isChanged
     * @param {Object} isTip 是否提示因时令改变而改变的号源
     * @param {Object} isTemp 是否是模板
     */
    appoPull(appoData, isChanged, isTip, isTemp) {
      console.log('appoData', appoData)
      isTip && setLocalStorage('yjyy-repair-opp', '')
      // 获取上下午班的时令
      let _sbData = JSON.parse(JSON.stringify(this.sidebardata)) // 哪里拿到的
      if (isTemp || this.statusTemplate == 'template') {
        _sbData = JSON.parse(JSON.stringify(getSidebarDataTemp() || this.sidebardata)) // 哪里拿到的
      } else {
        _sbData = JSON.parse(JSON.stringify(this.sidebardata)) // 哪里拿到的
      }
      // console.log('appoPull=>_sbData', _sbData)
      // 清空被勾选的id
      this.isCheckedIds = []
      // this.scheduledata是7天的初始化数据，里面还没号源，是空的
      // 初始化是否勾选全天半天的状态
      this.scheduledata.forEach(todayScheduleData => {
        todayScheduleData.checkedAll = false
        todayScheduleData.checkedAllHalf = {
          0: false
        }
        // 根据时令来初始化todayScheduleData.checkedAllHalf
        for (let i = 0; i < _sbData.length; i++) {
          todayScheduleData.checkedAllHalf[i] = false
        }
        todayScheduleData.appointment.forEach(timeFrameData => {
          timeFrameData.checkedAll = false
          timeFrameData.forEach(item => {
            item.isChecked = false
          })
        })
      })
      // // console.log('拿到所有的号源数据appoPull', appoData)
      // 把所传进来的号源数据都初始化为未选中状态
      appoData.forEach(item => {
        item.isChecked = false
      })
      // 初始化号源数据，把里头的添加号源item给过滤掉
      const initData = this.initData(JSON.parse(JSON.stringify(appoData)))
      console.log('initData', initData)
      // 处理过后的号源数据_appoData
      const _appoData = [...initData]
      const _week = this.week
      return new Promise((resolve, reject) => {
        // 窗体大小变化，自动改变列表最大值
        this.$_resizeHandler_fsc()
        let appoLen = _appoData.length
        let appoError = []
        let appoSucc = []
        // // // console.log('appoSuccappoSucc111', appoSucc)
        let appoOldData = JSON.parse(JSON.stringify(this.scheduledata))
        if (appoLen === 0) {
          resolve()
        }

        // 数据清空
        // 班次数组集合
        // // // console.log('班次数据源_sbData====>', _sbData) // 需查看班次数据源是哪里拿到的
        const appointen = this.getAppointentArr(_sbData)
        console.log('初始化appointen====>', appointen)
        appoOldData.forEach(schedule => {
          schedule.appointment = JSON.parse(JSON.stringify(appointen))
        })
        // 初始化是否修复了某条号源的班次
        isTip && setLocalStorage('isRepairCheckClass', 0)
        // // // console.log('组合后的班次数据源appoOldData === ', appoOldData) // 数据正常
        const start = async () => {
          let appoInfo = _appoData.shift()
          if (appoInfo) {
            appoInfo.timestamp = new Date().getTime() + Math.random() + Math.random()
          }
          if (appoLen === 0 && !appoInfo) {
            appoSucc.filter(a => !a.appoInfo.isAddBox).forEach((zappo, index) => {
              let { sidebarIndex, scheduleIndex, appoInfo } = zappo
              // appoInfo里竟然已经是修复了的时间
              const nObj = Object.assign({}, appoInfo)
              let oObj = (appoOldData[scheduleIndex].appointment[sidebarIndex] && JSON.parse(JSON.stringify(appoOldData[scheduleIndex].appointment[sidebarIndex]))) || []
              // console.log('==oObj==', oObj)
              let day = nObj.appointmentDate && nObj.appointmentDate.substring(0, 10)
              // const timeObj = _sbData[sidebarIndex]
              // const sidebarIndexNext = sidebarIndex + 1
              let timeObj = ''
              if (day && !isTemp) {
                const daySidebarData = getSidebarDataThisDay(day)
                if (!isNull(daySidebarData)) {
                  timeObj = daySidebarData[sidebarIndex || 0]
                } else {
                  timeObj = _sbData[sidebarIndex]
                }
              } else {
                // // console.log('_sbData', _sbData)
                timeObj = _sbData[sidebarIndex]
                // // console.log('DAY NOT timeObj', timeObj)
              }
              // // console.log('这里的数据是否还正常oObj', oObj)
              // 计算号源的样式以及修复班次
              // // console.log('修复班次:scheduleIndex,sidebarIndex', scheduleIndex, sidebarIndex)
              let nnobj = null
              // // console.log('nObj', nObj)
              if (!isNull(nObj)) {
                let timeObj2 = ''
                if (day) {
                  const daySidebarData = (!isTemp && getSidebarDataThisDay(day)) || null
                  if (!isNull(daySidebarData)) {
                    timeObj2 = daySidebarData[(sidebarIndex + 1) || 0]
                  } else {
                    timeObj2 = _sbData[(sidebarIndex + 1) || 0]
                  }
                } else {
                  timeObj2 = _sbData[(sidebarIndex + 1) || 0]
                }
                // // console.log('timeObj2===>1111111111', timeObj2)
                // // console.log('nObj.beginTime', getCalTimeMinute(nObj.beginTime))
                // // console.log('timeObj.start', getCalTimeMinute(timeObj.start))
                // // console.log('nObj.endTime', getCalTimeMinute(nObj.endTime))
                // // console.log('nObj', nObj)
                if (!isNull(timeObj) && getCalTimeMinute(nObj.beginTime) < getCalTimeMinute(timeObj.start) && getCalTimeMinute(nObj.endTime) <= getCalTimeMinute(timeObj.start)) {
                  // newIndex = sidebarIndex - 1
                  if (day) {
                    const daySidebarData = (!isTemp && getSidebarDataThisDay(day)) || null
                    if (!isNull(daySidebarData)) {
                      timeObj2 = daySidebarData[0]
                    } else {
                      timeObj2 = _sbData[0]
                    }
                  }
                }
                nnobj = calAppoStyleObj(timeObj, nObj, this.rowHeight, timeObj2)
              }
              // // console.log('========nnobjnnobjnnobj===========', nnobj)
              // 啊，这里过滤掉了有问题的数据
              // if (nnobj && !nnobj.isBad) {
              // 20231102取消过滤有问题的号源数据
              if (nnobj) {
                // // console.log('班次重组:scheduleIndex,sidebarIndex', scheduleIndex, sidebarIndex)
                // // console.log('nObj', nObj)
                // // console.log('timeObj', timeObj)
                // appoOldData[scheduleIndex].appointment[sidebarIndex] = isNull(oObj) ? [nnobj] : oObj.concat([nnobj])
                if (!isNull(timeObj) && getCalTimeMinute(nObj.beginTime) < getCalTimeMinute(timeObj.start) && getCalTimeMinute(nObj.endTime) <= getCalTimeMinute(timeObj.start)) {
                  const newSidebarIndex = sidebarIndex - 1
                  oObj = (appoOldData[scheduleIndex].appointment[newSidebarIndex] && JSON.parse(JSON.stringify(appoOldData[scheduleIndex].appointment[newSidebarIndex]))) || []
                  appoOldData[scheduleIndex].appointment[newSidebarIndex] = isNull(oObj) ? [nnobj] : oObj.concat([nnobj])
                  // // console.log(`appoOldData[${scheduleIndex}].appointment[${newSidebarIndex}]`, appoOldData[scheduleIndex].appointment[newSidebarIndex])
                } else {
                  appoOldData[scheduleIndex].appointment[sidebarIndex] = isNull(oObj) ? [nnobj] : oObj.concat([nnobj])
                  // // console.log(`appoOldData[${scheduleIndex}].appointment[${sidebarIndex}]`, appoOldData[scheduleIndex].appointment[sidebarIndex])
                }
              }
            })
            // console.log('JSON.stringify(appoOldData)', JSON.stringify(appoOldData)) // 数据正常
            let odata = JSON.parse(JSON.stringify(appoOldData))
            // console.log('odata', odata)
            // odata中时间有异常的号源数据已被自动修复时间？
            let sidebarDataT = isTemp ? (getSidebarDataTemp() || getSidebarData()) : getSidebarData()
            // // console.log('sidebarDataT', sidebarDataT)
            const newAppo = await this.getScheByTypes(odata, sidebarDataT, isTemp)
            // // // console.log('appoOldData数据通过this.getScheByTypes函数加工后得到下面最新的this.scheduledata')
            // 最终得到的数据源
            this.scheduledata = JSON.parse(JSON.stringify(newAppo))
            console.log('最终得到的数据源this.scheduledata', this.scheduledata)
            // 计算预约号源的当天总数
            this.calAppoTotal(this.scheduledata)
            // // console.log('时间出错数据：', appoError)
            // if (appoErrorHtmlStr) {
            //   appoErrorHtmlStr += `<div>时间出错，超出班次时间范围，将不显示以上时段号源，如保存、暂存或发布将删除以上时段号源！</div>`
            //   this.$alert(appoErrorHtmlStr, '时段号源时间出错提示', {
            //     dangerouslyUseHTMLString: true
            //   })
            // }
            if (appoError.length > 0) {
              this.$emit('appoErrorListChange', appoError)
            }
            // 判断为已改变，提交时做判断是否提交更新
            this.isChanged = !!isChanged
            // // console.log('appoPull:====', this.scheduledata)
            // 遍历设置左边班次时段状态，展开|收起
            this.sidebarHideShow()
            // 判断号源是否有修复过班次，若有就提示保存或发布
            if (isTip && getLocalStorage('isRepairCheckClass') == '1') {
              let repairOppList = getLocalStorage('yjyy-repair-opp')
              repairOppList = JSON.parse((repairOppList))
              repairOppList = repairOppList.map(item => {
                return `${item.week}的${item.beginTime}~${item.endTime}`
              })
              this.dialogTipVisible = true
              this.tipContent = `由于时令的改变，导致该机房：${repairOppList.join('、')}，等号源班次数据有重组，点击右上角的[${isTemp ? '保存' : '发布'}]按钮，重新${isTemp ? '保存' : '发布'}后才会生效！`
              // this.$alert(`由于时令的改变，导致该机房：${repairOppList.join('、')}，等号源班次数据有重组，点击右上角的[${isTemp ? '保存' : '发布'}]按钮，重新${isTemp ? '保存' : '发布'}后才会生效！`, '系统提示', {
              //   confirmButtonText: '确定'
              // })
            }
            // 任务执行完成
            resolve()
            return
          }
          try {
            let Zappo = { appoInfo: appoInfo }
            // // // // console.log('Zappo', Zappo)
            if (appoInfo) {
              // 班次名称判断转换 因为不去修复时间的需求，而在20231109号注释
              // const appoTitle = getSeasonDateTitle({
              //   appointmentDate: Zappo.appoInfo.appointmentDate,
              //   beginTime: Zappo.appoInfo.beginTime,
              //   endTime: Zappo.appoInfo.endTime
              // })
              // Zappo.appoInfo.checkClass = appoTitle || Zappo.appoInfo.checkClass
              if (appoInfo.week) {
                // 判断日期，获取日期索引
                Zappo.scheduleIndex = _week.findIndex(w => w === appoInfo.week)
              }
              // 获取 sidebarIndex
              const _sid = this.calSidebarIndex(appoInfo)
              // console.log('###_sid###', _sid)
              if (_sid >= 0) {
                Zappo.sidebarIndex = _sid
              } else {
                // 不正常数据
                console.log('不正常数据22222')
                appoError.push({ ...appoInfo })
              }
            }
            // 正常数据
            appoSucc.push(Zappo)
          } catch (err) {
            // 不正常数据
            console.log('不正常数据11111')
            appoError.push({ ...appoInfo })
          }
        }
        // 开始执行任务
        while (appoLen >= 0) {
          start()
          appoLen -= 1
        }
      })
    },
    // 数据导入，会覆盖原来的预约时段
    async appoImport(ImportAppointmentData, isWeek, isTemp) {
      console.log('ImportAppointmentData', ImportAppointmentData)
      // 1、遍历导入数据
      // 2、计算导入数据的日期，是星期几 ‘scheduleIndex’
      // 3、遍历导入的日数据
      // 4、计算时段时间所在时段‘sidebarIndex’，如：上午班、下午班。且导入时段数据不超出所在的时段最大最小时间范围。
      // 5、根据计算的 ‘scheduleIndex’、‘sidebarIndex’，计算日单条时段数据与所在日期时段的原始数据的交集情况
      // 6、根据计算的交集情况，如有交集，删除交集的原始数据。
      // 7、添加当前导入数据到计算出来的‘scheduleIndex’、‘sidebarIndex’日期时段。
      const IAppoData = JSON.parse(JSON.stringify(ImportAppointmentData.map(ia => ia.filter(a => !a.isAddBox))))
      const _sidebardata = this.sidebardata
      const _scheduledata = JSON.parse(JSON.stringify(this.scheduledata))
      return new Promise(async resolve => {
        if (isWeek) {
          _scheduledata.forEach((item, index) => {
            // 当天的数据过滤，改为直接替换导入数据，清空当前之前的数据
            _scheduledata[index].appointment = this.getAppointentArr(_sidebardata)
          })
        }
        console.log('IAppoData ===', IAppoData)
        IAppoData.forEach((iAppoDayList) => {
          if (iAppoDayList.length) {
            console.log('iAppoDayList ============', iAppoDayList)
            // 星期几
            const scheduleIndex = _scheduledata.findIndex(sche => sche.week === iAppoDayList[0].week)
            // if (!isWeek) {
            //   _scheduledata[scheduleIndex].appointment = this.getAppointentArr(_sidebardata)
            // }
            // 导入数据的 一天数据遍历
            iAppoDayList.forEach((iAppo) => {
              console.log('iAppo:=============', iAppo)
              // 加一个检查时间 appointmentDate: "2021-05-26 00:00:00"
              iAppo.appointmentDate = _scheduledata[scheduleIndex].dateFull + ' 00:00:00'
              iAppo.id = !iAppo.id && iAppo.id !== 0 ? 0 : iAppo.id
              iAppo.timestamp = new Date().getTime() + Math.random()

              let IminTime = iAppo.beginTime
              let ImaxTime = iAppo.endTime
              let ImaxMin = ImaxTime.split(':')[0] * 60 + ImaxTime.split(':')[1] * 1
              let IminMin = IminTime.split(':')[0] * 60 + IminTime.split(':')[1] * 1
              let sidebarIndex = -1
              // 班次名称判断转换
              const appoTitle = getSeasonDateTitle({
                appointmentDate: iAppo.appointmentDate,
                beginTime: iAppo.beginTime,
                endTime: iAppo.endTime,
                checkClassData: _sidebardata
              })
              // console.log('班次名称判断转换appoTitle', appoTitle)
              iAppo.checkClass = appoTitle || iAppo.checkClass
              // console.log('_sidebardata', _sidebardata)
              _sidebardata.forEach((sbd, sbIndex) => {
                // console.log('sbd.end====>', sbd.end)
                let minTime = sbd.start
                let maxTime = sbd.end
                let maxMin = maxTime.split(':')[0] * 60 + maxTime.split(':')[1] * 1
                let minMin = minTime.split(':')[0] * 60 + minTime.split(':')[1] * 1
                if ((IminMin >= minMin && ImaxMin <= maxMin) || (IminMin >= minMin && IminMin <= maxMin && ImaxMin >= maxMin)) {
                  // 判断星期几、判断时段内是否超出
                  sidebarIndex = sbIndex
                }
              })
              // console.log('scheduleIndex:====', scheduleIndex)
              // console.log('sidebarIndex:====', sidebarIndex)
              if (sidebarIndex >= 0) {
                let oldAppo = _scheduledata[scheduleIndex].appointment[sidebarIndex]
                const oldAppoLen = oldAppo.length
                if (oldAppoLen > 0) {
                  let lapNum = -1
                  oldAppo.forEach((oAppo, oAppoIndex) => {
                    let minTime = oAppo.beginTime
                    let maxTime = oAppo.endTime
                    let maxMin = maxTime.split(':')[0] * 60 + maxTime.split(':')[1] * 1
                    let minMin = minTime.split(':')[0] * 60 + minTime.split(':')[1] * 1
                    if (!(ImaxMin <= minMin && IminMin < minMin) && !(ImaxMin > maxMin && IminMin >= maxMin)) {
                      // 判断时段区间的交集情况
                      // 赋值交集数据的索引
                      lapNum = oAppoIndex
                    }
                  })
                  // 如有交集，删除原来交集数据
                  if (lapNum >= 0) {
                    oldAppo.splice(lapNum, 1)
                  }
                  // 添加导入数据
                  oldAppo.push({ ...iAppo })
                } else {
                  // 添加导入数据
                  oldAppo.push({ ...iAppo })
                }
              } else {
                // console.log('导入时段时间不在当前时段范围！')
              }
            })
            // // console.log('scheduleIndex:====', scheduleIndex)
          }
        })
        // console.log('_scheduledata:====', _scheduledata)
        // await getScheduleAppoSametype(_scheduledata)
        // 号源重新插入
        // console.log('号源重新插入')
        let appodata = []
        _scheduledata.forEach(sche => {
          let iScheAppoArr = sche.appointment
          iScheAppoArr = flattenDeep(iScheAppoArr)
          appodata.push(iScheAppoArr)
        })
        appodata = flattenDeep(appodata)
        // console.log('appodata', appodata)
        this.appoPull(appodata, true, null, true)

        // this.scheduledata = JSON.parse(JSON.stringify(_scheduledata))
        // 计算预约号源的当天总数
        this.calAppoTotal(this.scheduledata)
        // 判断为已改变，提交时做判断是否提交更新
        this.isChanged = true
        this.sidebarHideShow()
        resolve(true)
      })
    },

    // 设置初始展示数据，模拟数据
    setInitData() {
      const sideLen = this.sidebardata.length
      const scheLen = this.scheduledata.length
      for (let i = 0; i < sideLen; i++) {
        for (let j = 0; j < scheLen; j++) {
          const tg = this.sidebardata[i].timegather
          const timeLen = this.sidebardata[i].timegather.length
          const astatus = (Math.floor(Math.random() * 10) % 5) + ''
          for (let t = 0; t < timeLen; t++) {
            originObj.beginTime = tg[t].time.split('-')[0]
            originObj.endTime = tg[t].time.split('-')[1]
            originObj.initialNum = Math.floor(Math.random() * 30)
            originObj.checkNum = Math.floor(Math.random() * 30)
            originObj.appointmentStatus = astatus
            this.quickTempObjFul = Object.assign({}, originObj)
            this.appoAdd({ sidebarIndex: i, scheduleIndex: j, timeIndex: t })
          }
        }
      }
      this.quickTempObjFul = null
      originObj.appointmentStatus = ''
    },
    sidebarHideChange(index, type) {
      // // // // console.log('sidebarHideChange', index)
      // type 判断是否展开列表，在数据加载的时候传 type:true 默认有数据列表展开
      this.sidebardata[index].sidebarHide = type ? false : !this.sidebardata[index].sidebarHide
      // // // // console.log('sidebarHideChange', this.sidebardata[index])
      if (!this.sidebardata[index].sidebarHide) {
        this.sidebardata[index].barHeight = this.sidebardata[index].zanc.sbh
        this.sidebardata[index].timegather = this.sidebardata[index].zanc.stg
      } else {
        this.sidebardata[index].barHeight = this.sidebardata[index].zanc.hbh
        this.sidebardata[index].timegather = this.sidebardata[index].zanc.htg
      }
      this.sidebardata = JSON.parse(JSON.stringify(this.sidebardata))
      // // // // console.log(this.sidebardata[index].barHeight)
    },
    // 展开收起
    sidebarHideShow() {
      const appointent = this.getAppointentArr(this.sidebardata)
      const scheLen = this.scheduledata.length
      for (let i = 0; i < appointent.length; i++) {
        let count = 0
        for (let j = 0; j < scheLen; j++) {
          count += this.scheduledata[j].appointment[i].length
        }
        if (count > 0) {
          this.sidebarHideChange(i, true)
        }
      }
    },
    // 计算时段可以加的最小，最大号源区间
    getInitialMinMaxNum(beginTime, endTime) {
      // // // console.log('==beginTime', beginTime)
      // // // console.log('=============getInitialMinMaxNum_begin==============')
      // // // // console.log(beginTime, endTime)
      const sbIdx = this.sidebarIndex
      const sdIdx = this.scheduleIndex
      let bTime = beginTime ? beginTime.split(':')[0] * 60 + beginTime.split(':')[1] * 1 : 0
      let eTime = endTime ? endTime.split(':')[0] * 60 + endTime.split(':')[1] * 1 : 0

      const appoArr = this.scheduledata[sdIdx].appointment[sbIdx]
      // // // // console.log(appoArr)
      let minNum = 0 // 最小值为，所有值相加
      let maxNum = 0 // 最大值为，初始值
      if (appoArr.length > 0) {
        let minBTime = bTime + eTime
        let minCurrTime = 0
        let maxBTime = bTime + eTime
        let maxCurrTime = 0
        // // // console.log('appoArr', appoArr)
        appoArr.forEach(item => {
          // // // console.log('item.beginTime', item.beginTime)
          // // // console.log('item', item)
          if (item.beginTime < beginTime) {
            const bt = item.beginTime.split(':')[0] * 60 + item.beginTime.split(':')[1] * 1
            const et = item.endTime.split(':')[0] * 60 + item.endTime.split(':')[1] * 1
            const iTime = bt + et
            // // // console.log('minBTime', minBTime)
            // // // console.log('iTime', iTime)
            // // // console.log('minCurrTime', minCurrTime)
            // // // console.log('item.initialNum', item.initialNum)
            // // // console.log('item.checkNum', item.checkNum)
            // // // console.log('item.reserveNum', item.reserveNum)
            // // // console.log('item.addNum', item.addNum)
            if (minBTime > iTime && minCurrTime < iTime) {
              minCurrTime = iTime
              minNum = (item.initialNum * 1) + (item.checkNum * 1) + (item.reserveNum * 1) + (item.addNum * 1)
            }
            // // // console.log('maxBTime', maxBTime)
            // // // console.log('maxCurrTime', maxCurrTime)
            if (maxBTime < iTime && (iTime < maxCurrTime || maxCurrTime === 0)) {
              maxCurrTime = iTime
              maxNum = (item.initialNum * 1)
            }
            // if (minBTime > iTime && minCurrTime < iTime) {
            //   minCurrTime = iTime
            //   minNum = (item.initialNum * 1)
            // }
            // // // // console.log('maxBTime', maxBTime)
            // // // // console.log('maxCurrTime', maxCurrTime)
            // if (maxBTime < iTime && (iTime < maxCurrTime || maxCurrTime === 0)) {
            //   maxCurrTime = iTime
            //   maxNum = (item.initialNum * 1) + (item.checkNum * 1) + (item.reserveNum * 1) + (item.addNum * 1)
            // }
          }
          // // // console.log('=============getInitialMinMaxNum_End==============')
        })
      }
      // // // console.log('minNum, maxNum', minNum, maxNum)
      return { minNum, maxNum }
    },
    // 计算 sidebarIndex
    calSidebarIndex(appoInfo) {
      // console.log('appoInfo', appoInfo)
      let sidebarIndex = -1
      if (!appoInfo) return sidebarIndex
      // console.log('calSidebarIndex=>this.sidebardata', this.sidebardata)
      // if (isNull(this.sidebardata)) {
      //   this.sidebardata =
      // }
      this.sidebardata.forEach((item, index) => {
        const st = item.start.split(':')[0] * 60 + item.start.split(':')[1] * 1
        const et = item.end.split(':')[0] * 60 + item.end.split(':')[1] * 1
        const ost = appoInfo.beginTime.split(':')[0] * 60 + appoInfo.beginTime.split(':')[1] * 1
        const oet = appoInfo.endTime.split(':')[0] * 60 + appoInfo.endTime.split(':')[1] * 1
        // console.log('st', st)
        // console.log('et', et)
        // console.log('ost', ost)
        // console.log('oet', oet)
        if (ost >= st && (oet <= et || this.appoRepair)) {
          // 判断班次，获取班次索引
          sidebarIndex = index
        }
      })
      return sidebarIndex
    },
    // 窗体大小变化，自动改变列表最大值
    $_resizeHandler_fsc() {
      const fscRef = this.$refs.fullscheduleContainer
      if (fscRef) {
        this.$nextTick(() => {
          // this.fscHeight = fscRef.offsetTop + 25
          this.fscHeight = fscRef.getBoundingClientRect().top + 25
          this.fscStyle.height = `calc(100vh - ${fscRef.getBoundingClientRect().top + 25}px)`
          // // // // console.log(fscRef.getBoundingClientRect().top)
          // // // // console.log(fscRef.offsetWidth)
        })
      }
    }
  },
  beforeMount() {
    window.addEventListener('resize', this.$_resizeHandler_fsc)
  },
  beforeDestroy() {
    console.warn('号源组件销毁')
    this.$store.dispatch('user/getHospitalAppSettings', localStorage.getItem('roomCascaderHospCode') || localStorage.getItem('roomCascaderHospCode-' + this.$store.state.user.hospitalCode))
    window.removeEventListener('resize', this.$_resizeHandler_fsc)
  }
}
</script>

<style lang="scss" scoped>
@import '~@/styles/fullschedule.scss';
</style>
